package cn.yunyichina.provider.clinic.listener;

import cn.yunyichina.provider.clinic.service.impl.AsmServiceImpl;
import cn.yunyichina.provider.clinic.service.impl.PayServiceImpl;
import cn.yunyichina.provider.clinic.utils.DateUtils;
import cn.yunyichina.provider.framework.dubbo.service.BaseService;
import cn.yunyichina.provider.iface.entity.base.OrderExtVo;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.utils.convert.JsonUtils;
import cn.yunyichina.utils.convert.XmlUtils;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.listener.MessageListener;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by JoeZ on 2017/3/1.
 */
public class AsmWechatMessageListener  implements MessageListener<Integer, String> {

    private Logger logger = LoggerFactory.getLogger(AsmWechatMessageListener.class);

    @Autowired
    private PayServiceImpl payService;

    @Autowired
    private AsmServiceImpl asmService;

    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public void onMessage(ConsumerRecord<Integer, String> integerStringConsumerRecord) {

        String xmlString = integerStringConsumerRecord.value();
        logger.info("AsmWechatMessageListener.onMessage.xmlString -> {}", xmlString);
        Map<String, String> doc = XmlUtils.xmlToMap(xmlString);

        String appId = doc.get("appid");
        String orderNo = doc.get("out_trade_no");
        String openId = doc.get("openid");
        String attach = doc.get("attach");
        String bank_type = doc.get("bank_type");
        String fee_type = doc.get("fee_type");
        String transaction_id = doc.get("transaction_id");
        String mch_id = doc.get("mch_id");
        String nonce_str = doc.get("nonce_str");
        String sub_mch_id = doc.get("sub_mch_id");
        String time_end = doc.get("time_end");
        String totalFee = doc.get("total_fee");
        String resultCode = doc.get("result_code");

        Map<String, String> params = new HashMap<>();
        OrderExtVo order = new OrderExtVo();
        params.put("order_no",orderNo);
        Response response = BaseService.callHumpFromInternal("yyt.base.order.by.orderno.get", JsonUtils.toJsonString(params));
        if("0".equals(response.getResultCode())){
            order = JsonUtils.parseObject(response.getResult(), OrderExtVo.class);
            order.setIsPayHandled(1);//支付是否通知并处理0：否，1：是
            if("SUCCESS".equals(resultCode)){
                logger.info(orderNo + "交易成功");
                order.setTotalAmount(Integer.valueOf(totalFee));
                order.setPayAppId(appId);
                order.setPayTime(format.format(new Date()));
                order.setUpdateTime(format.format(new Date()));
                order.setPaymentDealId(transaction_id);
                order.setPayStatus((short) 3);
                order.setOrderStatus((short) 3);

                //调用支付结果通知
                Map<String, String> datas = new HashMap<>();
                datas.put("hospital_code" , order.getOrgCode());
                datas.put("branch_code" , order.getBarcode());
                datas.put("order_no" , order.getOrderNo());
                datas.put("payment_deal_id" , order.getPaymentDealId());
                datas.put("out_order_no" , order.getOutOrderNo());
                datas.put("pay_status" , String.valueOf(order.getPayStatus()));
                datas.put("pay_time" , order.getPayTime());
                datas.put("order_type" , String.valueOf(order.getOrderType()));
                datas.put("pay_mode" , String.valueOf(order.getPayMode()));
                datas.put("pay_amount" , String.valueOf(order.getPayAmount()));

                Response resultNotice = null;
                try {
                    resultNotice = asmService.paymentAsmResultNotice(JsonUtils.toJsonString(datas));
                    logger.info(">> Get PaymentResultNotice reslut_code:" + resultNotice.getResultCode() + " --- relsut_Message:" + resultNotice.getResultMessage());
                } catch (Exception e) {
                    logger.error("[AsmWechatMessageListener.GetPaymentAsmResultNotice === ]" , e);
                }

            }else{
                logger.info(orderNo + "交易失败");
                order.setPayStatus((short) 4);
                order.setOrderStatus((short) 4);
            }

            //更改订单状态
            response = BaseService.callHumpFromInternal("yyt.base.order.update", JsonUtils.toJsonString(order));
            if("0".equals(response.getResultCode())){
                logger.info(orderNo + "订单更新成功！");
            }

        }else{
            logger.info("未查询到交易订单...");
        }
    }
}
